<template>
  <div>
    <!-- 右边基本表格 -->
    <BasicTable @register="registerTable">
      <!-- 表格标题 -->
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ title }} </span>
      </template>
      <!-- 表格右上角自定义按钮 -->
      <template #toolbar>
        <a-button
          v-for="(item, index) in butData"
          :key="index"
          :type="item.btnType"
          @click="item.do"
          v-auth="item.auth"
        >
          <Icon v-if="item.icon" :icon="item.icon" /> {{ t(item.title) }}
        </a-button>
      </template>
      <!-- 表格插槽 -->
      <template #firstColumn="{ record }">
        <a @click="handleForm({ code: record.code })">
          {{ record.name }}
        </a>
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <FormAuthUser @register="registerAuthUserDrawer" @success="handleSuccess" />
    <FormImport @register="registerImportModal" @success="handleSuccess" />
    <SetBatchForm @register="registerSetBatchModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsBasCusBasCusList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, watch, ref, onMounted } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, useTable } from '/@/components/Table';
  import { basCusDelete } from '/@/api/bas/cus/basCus';
  import { listSet, customListData } from '/@/api/test/testData';
  import { tabConfigData, schemasData } from '/@/utils/custom';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import InputForm from './form.vue';
  import { useGlobSetting } from '/@/hooks/setting';
  import { downloadByUrl2 } from '/@/utils/file/download';
  import { useModal } from '/@/components/Modal';
  import FormImport from './formImport.vue';
  import SetBatchForm from './setBatchForm.vue'

  const props = defineProps({
    treeCode: String,
    treeName: String,
  });

  const { t } = useI18n('bas.cus.basCus');
  const { showMessage } = useMessage();

  let tableColumns = ref<any>([]);
  let butData = ref<any>([]);
  let actionColumnData = ref<ActionItem[]>([]);
  let layVoucherView = ref<any>({});
  let listTabConfig = ref<any>({});
  const getTitle = ref({
    // 表格标题图标
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: listTabConfig.value.title,
  });
  let title = ref('');

  //配置表单内容
  const searchForm = ref<FormProps>({
    baseColProps: { lg: 6, md: 8 }, // 表单栅格布局
    labelWidth: 90, // 表单标签宽度
    showAdvancedButton: true,
    schemas: [],
  });

  const actionColumn: BasicColumn = {
    width: 120, //操作按钮宽度
    // actions: (record: Recordable) => {
    //   actionColumnData.value.forEach((item) => {
    //     console.log(item, 'item');
    //     //  判断item.ifShow
    //     if (item.ifShow == '1') {
    //       if (item.title == '编辑') {
    //         item.onClick = () => handleForm({ code: record.code });
    //       }
    //       if (item.title == '删除') {
    //         item.popConfirm = {
    //           title: '是否确认删除数据',
    //           confirm: handleDelete.bind(this, { code: record.code }),
    //         };
    //       }
    //       if (item.title === '分配人员') {
    //         item.onClick = () => handleFormAuthUser({ code: record.code });
    //       }
    //       if (item.title === '设置首批') {
    //         item.onClick = () => handleFormAuthUser({ code: record.code });
    //       }
    //     }
    //   });
    //   return actionColumnData.value;
    // },
    actions: (record: Recordable) => {
      // 创建一个新数组，只包含满足显示条件的按钮
      return actionColumnData.value
        .filter((item) => item.ifShow == '1') // 只保留需要显示的按钮
        .map((item) => {
          // 为每个按钮创建一个新对象，避免修改原始数据
          const newItem = { ...item };
          if (newItem.title == '编辑') {
            newItem.onClick = () => handleForm({ code: record.code });
          }
          if (newItem.title == '删除') {
            newItem.popConfirm = {
              title: '是否确认删除数据',
              confirm: handleDelete.bind(this, { code: record.code }),
            };
          }
          if (newItem.title === '分配人员') {
            newItem.onClick = () => handleFormAuthUser({ code: record.code });
          }
          if (newItem.title === '设置首批') {
            newItem.onClick = () => handleSetBatchForm({ record: record });
          }
          return newItem;
        });
    },
  };

  const [registerDrawer, { openDrawer }] = useDrawer();

  const [registerTable, { reload, setProps, getForm }] = useTable({
    actionColumn: actionColumn,
    columns: tableColumns,
    formConfig: searchForm.value as FormProps,
    rowSelection: {
      type: 'checkbox',
    },
  });

  watch(
    () => props.treeCode,
    async () => {
      await getForm().setFieldsValue({
        clsCode: props.treeCode,
        'basCus.cusCls.name': props.treeName,
      });
      reload();
    },
  );

  onMounted(async () => {
    const res = await listSet({ viewCode: 'bas_cus_list001' });
    title.value = res.layVoucherView.name;
    layVoucherView.value = res.layVoucherView;

    tableColumns.value = layVoucherView.value.flistTabCols; //表格表头

    searchForm.value.schemas = schemasData(layVoucherView.value.listQuery.queryCols);

    butData.value = layVoucherView.value.headBtns; //表格右上角按钮
    butData.value.forEach((item) => {
      if (item.btnKey === 'btnAdd') {
        item.do = () => handleForm({});
      }
      if (item.btnKey === 'btnExport') {
        item.do = () => handleExport();
      }
      if (item.btnKey === 'btnImport') {
        item.do = () => handleImport();
      }
    });

    actionColumnData.value = layVoucherView.value.rowBtns; //表格行内按钮

    listTabConfig.value = tabConfigData(res.layVoucherView.listTabConfig);
    setProps({
      ...listTabConfig.value,
      api: customListData,
      beforeFetch: (params) => {
        for (const key in params) {
          if (Array.isArray(params[key])) {
            params[key + '_gte'] = params[key][0];
            params[key + '_lte'] = params[key][1];
            delete params[key];
          }
        }
        params.url = listTabConfig.value.api;
        return params;
      },
    });

    if (!listTabConfig.value.immediate) {
      reload();
    }
  });

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  async function handleDelete(record: Recordable) {
    const res = await basCusDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  async function handleExport() {
    const { ctxAdminPath } = useGlobSetting();
    downloadByUrl2({
      url: ctxAdminPath + '/bas/cus/exportData',
      params: getForm().getFieldsValue(),
    });
  }

  function handleSuccess() {
    reload();
  }

  const [registerImportModal, { openModal: importModal }] = useModal();

  function handleImport() {
    importModal(true, {});
  }

  const [registerSetBatchModal, { openModal: setBatchModal }] = useModal();

  function handleSetBatchForm(record: Recordable) {
    setBatchModal(true, record);
  }
</script>
